#include <iostream>
#include <cstdlib>
#include "Procotol.hpp"
#include "Socket.hpp"


void Usage(char *str)
{
    std::cout << std::endl
    << "Usabe: " << str << " + Server_ip + Server_port" << std::endl
    << std::endl;
}

std::string Operator = "+^#/-$@*#%";
//std::string Operator = "+-*/%";

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
    }

    srand(time(nullptr));
    ClientSock _sock;
    _sock.Socket();

    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    int count = 5; 
    int n = _sock.Connect(server_ip, server_port);
    if(!n)
        exit(-25);

    //请求网络服务
    int cnt = 0;
    while(cnt < 10)
    {
        cnt++;
        sleep(1);
        std::string msg;
        int i = 1;
        while(i--)
        {
          
            int x = rand() % 100 + 1;
            usleep(1111);
            int y = rand() % 100;
            usleep(2131);
            char op = Operator[rand() % Operator.size()];

            Request req(x, y, op);
            std::string _msg = req.serialize();
            msg += CustomProtoco::Encode(_msg);
        }

        std::cout << "===========第" << cnt << "次发送==========" << std::endl;
        std::cout << "message:" << std::endl << msg << std::endl ;
        int wn = Write(_sock.GetSock(), msg.c_str(), msg.size());
        if(wn < 0)
        {
            std::cout << "write error" << std::endl;
            exit(15);
        }

        char buffer[128];
        int rn = Read(_sock.GetSock(), buffer, sizeof(buffer));
        if(rn > 0)
        {
            buffer[rn] = '\0';
            std::cout << "获得原始数据:" << std::endl << buffer << std::endl;
            std::string text = buffer;
            do
            {
                std::string ans;
                CustomProtoco::Decode(text, ans);
                
                Response res;
                res.deserialize(ans) ;

                std::cout << "解析后数据:"<< std::endl << "answer:" << res._answer << "  code:" << res._code << std::endl << std::endl;
            }while(text.size());
        }
        else if(rn == 0) break;
        else break;
    }
    sleep(1);

    _sock.Close();
    return 0;
}